package order

import (
	"context"
	"math"

	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/comboingredient"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/ent/ingredient"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/internal/svc"
	"gitee.com/wenchangshou/simple-admin-pancakebot-rpc/types/pancakebot"
	"github.com/jinzhu/copier"

	"github.com/zeromicro/go-zero/core/errorx"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePancakebotOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreatePancakebotOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePancakebotOrderLogic {
	return &CreatePancakebotOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreatePancakebotOrder PancakebotOrder management
func (l CreatePancakebotOrderLogic) CreatePancakebotOrder(in *pancakebot.PancakebotOrderInfo) (resp *pancakebot.PancakebotOrderInfo, err error) {

	var comboObj *ent.Combo
	if comboObj, err = l.svcCtx.DB.Combo.Get(l.ctx, *in.ComboId); err != nil {
		return nil, err
	}

	comboIngredients, err := l.svcCtx.DB.ComboIngredient.Query().Where(comboingredient.ComboIDEQ(*in.ComboId)).Where(comboingredient.IngredientIDIn(in.ComboIngredient...)).All(l.ctx)
	if err != nil {
		return nil, err
	}
	price := comboObj.Price
	for _, obj := range comboIngredients {
		price += obj.Price
	}

	const epsilon = 0.01
	if math.Abs(price-float64(*in.Price)) > epsilon {
		logx.Errorf("价格不匹配: 计算价格=%.2f, 传入价格=%.2f, 差值=%.4f",
			price, float64(*in.Price), math.Abs(price-float64(*in.Price)))
		return nil, errorx.NewInvalidArgumentError("price error")
	}
	ingredients, err := l.svcCtx.DB.Ingredient.Query().Where(ingredient.IDIn(in.ComboIngredient...)).All(l.ctx)
	if err != nil {
		return nil, err
	}
	ingredientName := ""
	if len(ingredients) > 0 {
		ingredientName = ingredients[0].Name
		for _, obj := range ingredients[1:] {
			ingredientName += "+ " + obj.Name
		}
	}
	pancakebotOrder, err := l.svcCtx.DB.PancakebotOrder.Create().
		SetUserID(*in.UserId).
		SetDeviceID(*in.DeviceId).
		SetComboID(*in.ComboId).
		SetComboName(*in.ComboName).
		SetComboIngredient(ingredientName).
		SetPrice(price).
		SetOutletNo(0).
		SetPayStatus(false).
		SetOrderStatus(1).
		Save(l.ctx)
	if err != nil {
		return nil, err
	}
	resp = &pancakebot.PancakebotOrderInfo{}
	err = copier.Copy(resp, pancakebotOrder)
	if err != nil {
		return nil, err
	}

	return resp, nil
}
